
#include<iostream>
#include<cerrno>
#include<string>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>


int main()
{

    const uint16_t port = 8080;
    //创建套接字
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        std::cout<<"sock error : "<<errno<<std::endl;
        return 1;
    }

    //1.设置端口和IP，sockaddr_in是一个描述服务器文件结构体
    struct sockaddr_in local;
    local.sin_family = AF_INET;
    local.sin_port = htons(port);

    //默认
    local.sin_addr.s_addr = INADDR_ANY;

    //bind绑定服务器
    if(bind(sock,(struct sockaddr*)&local,sizeof(local)) < 0)
    {
        //绑定失败
        std::cout<<"bind error : "<<errno<<std::endl;
    }

    //服务器提供服务
    char Buffer[1024];
    while(true)
    {
        struct sockaddr_in tmp;
        socklen_t len= sizeof(tmp);
        //接收数据
        int cnt = recvfrom(sock,Buffer,sizeof(Buffer)-1,0,(struct sockaddr*)&tmp,&len);
        if(cnt > 0)
        {
            //输出
            std::cout<<"client # "<<Buffer<<std::endl;
            std::string s("");
            //s +="server # ";
            s += Buffer;
            //数据发送给客户端
            sendto(sock,s.c_str(),s.size(),0,(struct sockaddr*)&tmp,len);
            Buffer[0] = 0;
        }
    }

    return 0;
}